//
//  ImageCell.m
//  KuWoCan
//
//  Created by hwd on 17/3/6.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "ImageCell.h"

@implementation ImageCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = 0;
    }
    return self;
    
}
-(void)loadCellWithTitle:(NSString *)title Imgae:(UIImage *)image
{
    for (UIView *view in self.contentView.subviews) {
        [view removeFromSuperview];
    }
    CanLab *_titleLab = [[CanLab alloc]initWithFrame:CGRectMake(20*screenW_6, 0, 15*5*screenW_6, 150*screenW_6) textAligment:0 font:14*screenW_6 textColor:@"#333333" text:title];
    _titleLab.numberOfLines = 0;
    _titleLab.textAlignment = NSTextAlignmentCenter;
    _titleLab.textColor = [UIColor grayColor];

    [self.contentView addSubview:_titleLab];
    
    CanView *imageBaseView = [[CanView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_titleLab.frame)+25*screenW_6, 25*screenW_6, 100*screenW_6, 100*screenW_6) backGroundColor:@"ECEEEE" Alpha:1];
    [self.contentView addSubview:imageBaseView];
    
    _picBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _picBtn.frame = CGRectMake(imageBaseView.origin.x, imageBaseView.origin.y, imageBaseView.bounds.size.width, imageBaseView.bounds.size.height);
    [_picBtn setImage:kImg(@"camera") forState:UIControlStateNormal];
    _picBtn.backgroundColor = KwGaryColor;
    [_picBtn addTarget:self action:@selector(choosePhotoSource) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_picBtn];

    [self.contentView addSubview:[ToolViewViewController addCellLineLab:CGRectMake(20*screenW_6, 149*screenW_6, SCREENW-40*screenW_6,1*screenW_6)]];
}


#pragma mark  - Take Photo

- (void)choosePhotoSource
{

    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    
    if (iOS8Later) {
        UIAlertController *alertControl = [[UIAlertController alloc] init];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
            
        }];
        
        UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
            [self takePhotoFormCamera];
        }];
        
        UIAlertAction *takeLibraryAction = [UIAlertAction actionWithTitle:@"使用相册图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
            [self takePhotoFormLibrary];
        }];
        
        [alertControl addAction:cancelAction];
        [alertControl addAction:takePhotoAction];
        [alertControl addAction:takeLibraryAction];
        
        [self.vc presentViewController:alertControl animated:YES completion:nil];
        
    }else {
        UIActionSheet *photoSheet = [[UIActionSheet alloc] initWithTitle:@"上传图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"使用相册图片", nil];
        [photoSheet showInView:[CommonTool getCurrtenViewCtrWithView:self].view];
    }
    
}

#pragma mark - Photo Method
- (void)takePhotoFormCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self.vc presentViewController:picker animated:YES completion:nil];
    }else {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"该设备找不到相机"];
    }
    
}

- (void)takePhotoFormLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [SVProgressHUD show];
    [self.vc presentViewController:picker animated:YES completion:^{
        [SVProgressHUD dismiss];
    }];
}
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (image == nil)
    {
        return;
    }
    //上传
    [self uploadImageWithImage:image];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImageWithImage:(UIImage *)image
{
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyyMMddhhmmss"];
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName =  [NSString stringWithFormat:@"%@IMG%@%@.png",kUploadImgPath,str,[Constants createUUID]];
        
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
        OSS_Request *request = [[OSS_Request alloc]init];
        [request uploadFileSyscToOSSWithData:imageData destinationFileName:fileName progressBlock:nil completeHandler:^(BOOL isSuccess, NSError *error, NSString *url) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            if (isSuccess)
            {
                //图片上传成功  开始发送请求
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_picBtn setImage:image forState:UIControlStateNormal];
                    if (weakSelf.type == CellTypeBuness)
                    {
                        //营业执照
                        [NSUserDefaults saveObject:url forKey:kUserInfo_BusinessLicense];
                        if (_block)
                        {
                            _block();
                        }
                    }
                    else
                    {
                        //食品
                        [NSUserDefaults saveObject:url forKey:kUserInfo_FoodCertificate];
                        if (_block)
                        {
                            _block();
                        }
                    }
                });
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:@"图片上传失败"];
                });
            }
            
        }];
    });
    
}


#pragma mark - UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            [self takePhotoFormCamera];
        }
            break;
        case 1:
        {
            [self takePhotoFormLibrary];
        }
            break;
        default:
            break;
    }
}



@end
